package com.czk.service;

import com.alibaba.fastjson.JSON;
import com.czk.entity.Content;
import com.czk.utils.HtmlParseUtils;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author:ChenZhangKun
 * @Date: 2020/12/15 17:33
 */
@Service
public class ContentService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 解析集合放在es中
     *
     * @param keywords
     * @return
     */
    public boolean parseContent(String keywords) {
        try {
            List<Content> list = HtmlParseUtils.parseJD(keywords);
            // 创建批量添加
            BulkRequest bulkRequest = new BulkRequest();
            // 设置过期时间
            bulkRequest.timeout("60s");
            for (int i = 0; i < list.size(); i++) {
                bulkRequest.add(
                        new IndexRequest("jd_goods")
                                .source(JSON.toJSONString(list.get(i)), XContentType.JSON)
                                .id(i + 1 + "")
                );
            }
            BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
            return !bulk.hasFailures();
        } catch (IOException ex) {

        }
        return false;
    }

    public List<Map<String, Object>> searchPage(String keywords, int pageNo, int pageSize) throws IOException {
        if (pageNo < 1) {
            pageNo = 1;
        }
        // 该库是否存在
        GetIndexRequest getRequest = new GetIndexRequest(keywords);
        boolean exists = restHighLevelClient.indices().exists(getRequest, RequestOptions.DEFAULT);
        if (!exists) {
            // 创建索引库
            CreateIndexRequest createIndexRequest = new CreateIndexRequest(keywords);
            CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
            if (!createIndexResponse.isAcknowledged()) {
                System.out.println("创建索引库" + keywords + "失败");
                return null;
            }
            // 爬取数据
            List<Content> list1 = HtmlParseUtils.parseJD(keywords);
            // 批量添加
            BulkRequest bulkRequest = new BulkRequest();
            for (int i = 0; i < list1.size(); i++) {
                bulkRequest.add(new IndexRequest(keywords).id(i + 1 + "").source(JSON.toJSONString(list1.get(i)), XContentType.JSON));
            }
            // 执行批处理请求
            restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        }
        // 条件搜索
        SearchRequest searchRequest = new SearchRequest(keywords);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 分页
        searchSourceBuilder.from(pageNo);
        searchSourceBuilder.size(pageSize);
        // 精准匹配
        TermQueryBuilder title = QueryBuilders.termQuery("title", keywords);
        searchSourceBuilder.query(title);
        // 构建高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        // 多个高亮时关闭
        highlightBuilder.requireFieldMatch(false);
        searchSourceBuilder.highlighter(highlightBuilder);


        // 执行搜索
        searchRequest.source(searchSourceBuilder);
        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        // 拿到结果
        List<Map<String, Object>> list = new ArrayList<>(10);
        SearchHit[] hits = search.getHits().getHits();
        for (SearchHit hit : hits) {
            // 结果封装高量
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField title1 = highlightFields.get("title");
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            if (title1 != null) {
                // 拿到高亮的字段
                Text[] fragments = title1.fragments();
                String newTitle = "";
                for (Text fragment : fragments) {
                    newTitle += fragment;
                }
                // 替换原来的内容
                sourceAsMap.put("title", newTitle);
            }
            list.add(sourceAsMap);
        }
        return list;
    }
}
